package com.sec.moveFile.utils;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author 68300119
 */
@Component
public class S3Util {

    /**
     * aws s3 client
     */
    AmazonS3 s3 = null;

    @Value("${ssc.s3.accessKeyId}")
    private String accessKeyId;
    @Value("${ssc.s3.accessKeySecret}")
    private String accessKeySecret;
    @Value("${ssc.s3.bucketName}")
    private String bucketName;
    @Value("${ssc.s3.endPoint}")
    private String endPoint;

    @PostConstruct
    public void init() {
        ClientConfiguration config = new ClientConfiguration();
        // S3最大连接数 跑完文件迁移之后删除或减小
        config.setMaxConnections(2000);
        config.setConnectionTimeout(30*1000);
        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(endPoint, "ap-northeast-2");

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, accessKeySecret);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

        s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
    }


    /**
     * 文件上传
     *
     * @param file 文件
     * @return uri
     */
    public String upload(MultipartFile file) {
        String fileName = String.format("%s.%s", UUID.randomUUID(),
                FilenameUtils.getExtension(file.getOriginalFilename()));
        String prefix = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String url = prefix + "/" + fileName;

        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(file.getContentType());
        objectMetadata.setContentLength(file.getSize());

        try {
            s3.putObject(bucketName, url, file.getInputStream(), objectMetadata);
        } catch (AmazonServiceException | IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        return url;
    }

    /**
     * 文件迁移用 用完就删除
     *
     * @param resource
     * @param url
     * @return
     */
    public String upload(Resource resource, String url) {
        try {
            InputStream inputStream = resource.getInputStream();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            s3.putObject(bucketName, url, inputStream, metadata);
        } catch (Exception e) {
            throw new RuntimeException("s3fail:" + e.getMessage());
        }

        return url;
    }

    /**
     * 文件下载
     *
     * @param url 文件路径
     * @return Resource
     */
    public Resource download(String url) {
        Resource resource = null;
        try {
            InputStream input = s3.getObject(bucketName, url).getObjectContent();
            resource = new InputStreamResource(input);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return resource;
    }

    public Boolean getHead(String url) {
        ObjectMetadata objectMetadata = s3.getObjectMetadata(bucketName, url);
        return true;
    }


}